package org.shock.ss.sms.commons.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Clob;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Util {
	private static final int BUFFER_SIZE = 16 * 1024;
	public static String DateToString(String date, String str1, String str2) {
		if (null == date || "".equals(date.trim()) || 0 == date.trim().length()) {
			return null;
		}
		try {
			SimpleDateFormat sdf1 = new SimpleDateFormat(str1);
			SimpleDateFormat sdf2 = new SimpleDateFormat(str2);
			return sdf2.format(sdf1.parse(date));
		} catch (Exception e) {
			// System.out.println("ʱ��ת������:" + e);
		}
		return date;
	}

	public static boolean isEmpty(String str) {
		return null == str || "".equals(str) || str.trim().length() == 0
				|| "null".equals(str);
	}

	public static String nulltoempty(String s) {
		return isEmpty(s) ? "" : s.trim();
	}

	public static String staticTime(String str, int monday, int day, String time) {
		SimpleDateFormat sdf = new SimpleDateFormat(str);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());

		if (monday != 0) {
			calendar.set(Calendar.MONDAY, calendar.get(Calendar.MONDAY)
					- monday);
		}

		if (day != 0) {
			if (day == 31) {
				int y = calendar.get(Calendar.MONDAY);
				if (y == 3 || y == 5 || y == 8 || y == 10) {
					day = 30;
				} else if (y == 1) {
					day = 28;
				}
			}
			calendar.set(Calendar.DAY_OF_MONTH, day);
		}
		time = isEmpty(time) ? "" : time;
		return sdf.format(calendar.getTime()) + time;
	}

	public static float getBl(int csnum, int pcsnum, int priont) {
		return 0 == pcsnum ? 0 : (float) Math.round((double) csnum / pcsnum
				* (100 * (int) (Math.pow(10, priont))))
				/ (int) (Math.pow(10, priont));
	}

	public static String ClobToString(Clob clob) {

		if (clob == null) {
			return "";
		}
		Reader is = null;
		BufferedReader br = null;
		StringBuffer sb = null;

		try {
			is = clob.getCharacterStream();
			br = new BufferedReader(is);
			sb = new StringBuffer("");
			String s = br.readLine();
			while (s != null) {
				sb.append(s);
				s = br.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}


	/**
	 * 将object的转化为String，null ,"" 都返回"" 其他的去掉首尾空格返回
	 * 
	 * @param obj
	 * @return
	 */
	public static String objToString(Object obj) {
		String value = "";
		value = null == obj ? "" : obj.toString().trim();
		return value;
	}

	/**
	 * 根据样式查出来当前时间
	 * 
	 * @param parttern
	 *            形如“yyyy-MM-dd”的模板,yyyy-MM-dd HH:mm:ss
	 * @return String 形如“yyyy-MM-dd”的模板的当前时间
	 */
	public static String getTime(String parttern) {
		parttern = parttern == null ? "yyyy-MM-dd" : parttern;
		return new SimpleDateFormat(parttern).format(new Date());
	}

	/**
	 * 得到当前时间 格式 2010-09-25 10:55:41
	 * 
	 * 
	 * @return String 形如“2010-09-25 10:55:41”的模板的当前时间
	 */
	public static String getXxTime() {
		return getTime("yyyy-MM-dd HH:mm:ss");
	}
	/**
	 * 格式化数字
	 * @param formatString格式如 0.00
	 * 
	 * @return String 形如“2010-09-25 10:55:41”的模板的当前时间
	 */
	public static String formatNumber(String formatString,double dob) {
		DecimalFormat format=new DecimalFormat(formatString);
		return format.format(dob);
	}
	/**
	 * 把是null的数值类型的包装类的值初始为0
	 * 
	 * @param number
	 *            Object 数值类型的包装类
	 * @return Object 数值类型的包装类
	 */
	public static Object nullToZero(Object number) {
		return number == null ? 0 : number;
	}

	/**
	 * 把汉字转码的方法
	 * 
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		try {
			return str == null ? "" : URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	/**
	 * 从数据字典中读取一系列key的value返回,如传入",1,2,"字符串返"张三,李四,"的值
	 * 
	 * @param keys
	 * @param dicMap
	 * @return String
	 */
	public static String getDataValue(String keys, Map<String, String> dicMap) {
		keys = keys == null ? "" : keys;
		String[] keyArray = keys.split(",");
		StringBuffer sb = new StringBuffer();
		for (String key : keyArray) {
			if (dicMap.containsKey(key)) {
				sb.append(",").append(dicMap.get(key));
			}
		}
		sb.replace(0, 1, "");
		return sb.toString();
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param bg
	 * @param end
	 * @return
	 */
	public static long datedif(String bg, String end) {
		long day = 0;
		try {
			day = (new SimpleDateFormat("yyyy-MM-dd").parse(bg).getTime() - new SimpleDateFormat(
					"yyyy-MM-dd").parse(end).getTime()) / (3600 * 24 * 1000);
		} catch (ParseException e) {
			throw new RuntimeException("日期格式不匹配！请用yyyy-MM-dd格式！");
		}
		return Math.abs(day);
	}

	/**
	 * 计算某一日期与今天相差的天数
	 * 
	 * @param bg
	 * @return
	 */
	public static long datedif(String bg) {
		long day = 0;
		try {
			day = (new SimpleDateFormat("yyyy-MM-dd").parse(bg).getTime() - System
					.currentTimeMillis()) / (3600 * 24 * 1000);
		} catch (ParseException e) {
			throw new RuntimeException("日期格式不匹配！请用yyyy-MM-dd格式！");
		}
		return Math.abs(day);
	}

	/**
	 * 公用的获取文件的后缀名
	 * @param fileName 文件名
	 * @return 若无后缀名就返回“”；
	 * @throws Exception
	 */
	public static String getExtention(String fileName) throws Exception {
		fileName=null==fileName ? "" : fileName.trim();
		int pos = fileName.lastIndexOf(".");
		if(pos!=-1){
			return fileName.substring(pos);
		}else{
			return fileName;
		}
	}
	
	
	
	/**
	 * 公用的copy文件的方法，
	 * @param src 源文件
	 * @param dst 拷贝的目的文件
	 */
	 public static void copy(File src, File dst) {
			try {
				InputStream in = null;
				OutputStream out = null;
				if(src.length()>0){//判断源文件的大小
				try {
					in = new BufferedInputStream(new FileInputStream(src),
							BUFFER_SIZE);
					out = new BufferedOutputStream(new FileOutputStream(dst),
							BUFFER_SIZE);
					byte[] buffer = new byte[BUFFER_SIZE];
					while (in.read(buffer) > 0) {
						out.write(buffer);
					}
				} finally {
					if (null != in) {
						in.close();
					}
					if (null != out) {
						out.close();
					}
				}
				}else{//源文件的大小为0则只生成一个0字节的文件
					OutputStreamWriter os = null;
		                os = new OutputStreamWriter(new FileOutputStream(dst));
		            os.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	
	 
	 /**
	  * 通过给定的正则表达式验证字符串
	  * @param match 正则表达式
	  * @param str 要验证的字符串
	  * @return 验证正确返回true，验证错误返回false；
	  */
	 public static boolean matchString(String match,String str){
		boolean res=false;
		Pattern p=Pattern.compile(match);
		Matcher m=p.matcher(str);
		res=m.matches();
		return res;
	 }
	 
	 /**
	  * 验证手机号码是否正确
	  * @param phone 需要验证的手机号码字符串
	  * @return 验证正确返回true，验证错误返回false；
	  */
	 public static boolean matchPhone(String phone){
		boolean res=false;
		if(null==phone){
			return false;
		}
		String match="^1[358]\\d{9}$";
		phone=phone.replaceAll("\\s*|\t|\r|\n","");//去除字符串中的空格,回车,换行符,制表符
		if(phone.length()==11){
			phone=phone.substring(0,11);
		}else {
			return false;
		}
		res=matchString(match, phone);
		return res;
	 }
	 
	 /**
	  * 删除指定文件夹内所有的文件
	  * @param filePath 指定的文件夹路径
	  * @return
	  */
	public static int delFiles(String filePath){
		File[] files=new File(filePath).listFiles();
		for(int i=0;i<files.length;i++){
			File delFile=new File(files[i].getPath());
			delFile.delete();
		}
		return 0;
	}
	 
	 
	
	public static void main(String[] args) {
		System.out.println(matchString("^1[358]\\d{9}$", "13111111111"));
	}
}